package com.alibaba.cloud.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.Optional;

/**
 * @Author liuzhihao
 * @Date 2022.01.09
 * @Version ${version}
 * @Description 解决循环依赖问题
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Slf4j
public class SentinelWebAutoConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private SentinelProperties sentinelProperties;

    @Autowired
    private Optional<SentinelWebInterceptor> sentinelWebInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        if (!sentinelWebInterceptor.isPresent()) {
            return;
        }
        SentinelProperties.Filter filterConfig = sentinelProperties.getFilter();
        registry.addInterceptor(sentinelWebInterceptor.get())
                .order(filterConfig.getOrder())
                .addPathPatterns(filterConfig.getUrlPatterns());
        log.info(
                "[Sentinel Starter] register SentinelWebInterceptor with urlPatterns: {}.",
                filterConfig.getUrlPatterns());
    }
}
